import React, { Component } from "react";
import { Toast, Carousel, Modal } from "antd-mobile";
import MainLayout from "@/component/mainLayout/mainLayout";
import settingIcon from "@images/setting.png";
import XHQBConfig from "@/config/XHQBConfig";
import { InterfaceG } from "@config/Config";
import { openWebView } from "@tools/native/navigate";
import Swiper from "@component/scrollxImage";
import copy from "copy-to-clipboard";
import yhTools from "@/tools/yh";
import { connect } from "react-redux";
import Banner from "@/views/viewCommon/Banner";

import { channelCode } from "@/config/Config";
import "./index.scss";

import ActivityModal from "@component/activityModal";
import xhqb_avatar from "@/images/xhqb_avatar.png";
import bank_icon from "@/images/icon/ic_me_yhk.png";
import kajuan_icon from "@/images/icon/ic_me_kqzx.png";
import fukuan_icon from "@/images/icon/ic_me_fkm.png";
import caifu_icon from "@/images/icon/ic_me_cf.png";
import jieqian_icon from "@/images/icon/ic_me_jq.png";
import tuiguang_icon from "@/images/icon/ic_me_tgyl.png";
import wenti_icon from "@/images/icon/ic_me_cjwt.png";
import footer from "@/images/imageXHF/xhf_foot.png";
import ic_xianshi from "@/images/icon/ic_xianshi.png";
import ic_buxianshi from "@/images/icon/ic_buxianshi.png";
import real_name from "@/images/real-name.png";
import ic_hp_gzw from "@/images/icon/ic_me_gzw.png";
import ic_me_qbzd from "@/images/icon/ic_me_qbzd.png";
import { billReportUrl } from "@/tools/utils";

const modalAlert = Modal.alert;
/**
 * 小辉钱包首页
 */
const funNavs = [
	{
		type: "1",
		name: "银行卡管理",
		icon: bank_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "3",
		name: "卡券中心",
		icon: kajuan_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "4",
		name: "付款码",
		icon: fukuan_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "5",
		name: "财富",
		icon: caifu_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "6",
		name: "借钱",
		icon: jieqian_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "7",
		name: "推广有礼",
		icon: tuiguang_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)",
		hidden: true
	},
	{
		type: "8",
		name: "常见问题",
		icon: wenti_icon,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "10",
		name: "关注我",
		icon: ic_hp_gzw,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	},
	{
		type: "11",
		name: "钱包账单",
		icon: ic_me_qbzd,
		shadow: "0px 0.2rem 0.24rem 0px rgba(221, 221, 221, 0.27)"
	}
];
@connect(state => state)
class HomeIndexpage extends Component {
	constructor(props) {
		super(props);
		this.state = {
			hasSetPassword: "", //是否设置支付密码
			mobilePhone: "", //手机号码
			totalAmount: "", //总资产
			totalProfit: "", //累计收益
			titleAmt: "", //本期账单
			title: "",
			titleStatus: "", //账单描述
			xhbStatus: "", //小辉宝开通状态
			xhbAmount: "", //小辉宝余额
			xhbRate: "", //小辉宝利率
			xhfStatus: "", //小辉付开通状态
			xhfAvailableAmount: "", //小辉付可用额度
			xhfMaxAmount: "", //小辉付总额度
			xhdStatus: "", //小辉贷开通状态
			xhdAvailableAmount: "", //小辉贷可用额度
			xhdMaxAmount: "", //小辉贷授信额度
			bannerList: [], //底部banner
			bankWelfareBanner: [], //银行福利banner
			selectIndex: "0", //当前产品
			showAmt: false,
			realVisible: false, //实名弹窗
			activeVisible: false, //活动弹窗
			activeData: {}, //活动数据
			buttonArray: [],
			realExhibition: false // 是否展示山西证券
		};
		this.tabNavs = ["信用付", "财富", "借钱"];
	}
	replaceStar(str) {
		if (typeof str !== "string") {
			return "";
		}
		let length = str.length;
		if (length < 7) {
			return str;
		}
		let star = "*".repeat(length - 7);
		return str.replace(/^(\d{3})\d*(\d{4})|(x)$/, `$1${star}$2`);
	}
	componentDidMount() {
		this.init();
		this.queryPopupFrameRule();
	}
	onRef = ref => {
		this.child = ref;
	};
	init = () => {
		Toast.loading("加载中...", 100);
		let objs = {
			url: XHQBConfig.queryMemberInfo,
			params: {
				channelCode: channelCode
			},
			_alertShow: false
		};
		let _that = this;
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				Toast.hide();
				let {
					xhbInfo,
					xhfInfo,
					xhdInfo,
					assets,
					xhfAmountDTO,
					hasSetPassword,
					mobilePhone,
					inviteActivityResp,
					realName,
					realExhibition
				} = res.data;
				if (
					realExhibition &&
					yhTools.getSdkVersion(
						this.props.getAppPlatformsDatas.sdkVersionCode
					) >= 105
				) {
					this.tabNavs.push("机构专区");
				}
				_that.setState(
					{
						realExhibition,
						hasSetPassword,
						mobilePhone,
						totalAmount: assets.totalAmount,
						totalProfit: assets.totalProfit,
						xhfAmountDTO: xhfAmountDTO,
						titleAmt: xhfAmountDTO.titleAmt,
						title: xhfAmountDTO.title,
						titleStatus: xhfAmountDTO.titleStatus,
						xhbStatus: xhbInfo.state,
						xhbAmount: xhbInfo.amount,
						xhbRate: xhbInfo.rate,
						xhfStatus: xhfInfo.state,
						xhfAvailableAmount: xhfInfo.availableAmount,
						xhfMaxAmount: xhfInfo.maxAmount,
						xhdStatus: xhdInfo.state,
						xhdAvailableAmount: xhdInfo.availableAmount,
						xhdMaxAmount: xhdInfo.maxAmount,
						bannerList: [],
						realVisible: !realName,
						realName: !realName
					},
					() => {
						this.child.updateSlides();
					}
				);
				if (inviteActivityResp) {
					this.queryInviteEffect(inviteActivityResp);
				}
				this.getBannerList();
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	//获取活动弹窗
	queryPopupFrameRule = () => {
		let objs = {
			url: InterfaceG.queryPopupFrameRule,
			params: {
				pageCode: "walletHomePage",
				productCode: "00"
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				if (res.data) {
					console.log(JSON.parse(res.data.buttonArray));
					this.setState({
						activeData: res.data,
						activeVisible: true,
						buttonArray: res.data.buttonArray
							? JSON.parse(res.data.buttonArray)
							: []
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	//获取底部轮播图
	getBannerList = () => {
		let objs = {
			url: InterfaceG.getBannerListByPageType,
			params: {
				pageType: "moneyPage"
			},
			_alertShow: false
		};
		let _that = this;
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				let list = [];
				if (res.data && res.data.length > 0) {
					res.data.forEach(item => {
						if (item.bannerType == "moneyPage_bottemBanner") {
							list = item.indexServerDtos;
						} else if (item.bannerType == "bankWelfareBanner") {
							_that.setState({
								bankWelfareBanner: item.indexServerDtos
							});
						}
					});
				}
				_that.setState({
					bannerList: list
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	/* 判断是否设置过密码 */
	gotoPaymentmanagement = () => {
		const { hasSetPassword, mobilePhone } = this.state;
		if (hasSetPassword == "0") {
			/* 密码修改页面 */
			window.sessionStorage.setItem("phone", JSON.stringify(mobilePhone));
			this.props.history.push({
				pathname: "/setup",
				query: {
					//随便传一个参数，小辉宝主页识别query，判断是否正常返回还是关闭SDK
					realVisible: this.state.realName
				}
			});
		} else if (hasSetPassword == "1") {
			/* 密码设置页面 */
			this.props.history.push({
				pathname: "/settransactionpassword",
				query: { name: "index" }
			});
		}
	};
	//产品tab切换
	handleSelectPro = index => {
		this.child.handleTo(index);
		this.setState({
			selectIndex: index
		});
	};
	handleSetSelect = index => {
		this.setState({
			selectIndex: index
		});
	};
	//跳转页面
	jumpPage(url, Urlparams) {
		this.props.history.push({
			pathname: url,
			state: Urlparams
		});
	}
	handleClickPayCode = () => {
		const { xhfStatus } = this.state;
		if (xhfStatus === "1") {
			//已开通小辉付
			this.goPaymentCode();
		} else {
			// 未开通，去开通
			this.props.history.push({
				pathname: "/xhfHomeNoCredit",
				query: {
					//随便传一个参数，小辉付主页识别query，判断是否正常返回还是关闭SDK
					from: "/xhqbIndex"
				}
			});
		}
	};
	//跳转付款码页面
	goPaymentCode() {
		let objs = {
			url: InterfaceG.appBtnPaymentCode,
			params: {
				version: "1.0"
			}
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				const pageNo = res.data.pageNo;
				const pageName = res.data.pageName;
				switch (pageNo) {
					case "7": // 7 付款码
						this.jumpPage("/payCode");
						break;
					case "8": //8 设置支付密码
						this.props.history.push({
							pathname: "/xhfSetPasswordPage",
							state: {
								gotoNext: "edjh"
							}
						});
						break;
					case "13": //逾期情况
						modalAlert("", pageName, [
							{
								text: "去还款",
								onPress: () => {
									this.jumpPage("/billHome");
								}
							}
						]);
						break;
					case "14": //额度不足
						Toast.info(pageName, 2);
						break;
					case "15": //激活页面
						this.jumpPage("/xhfFacilitySuccess");
						break;
					default:
						break;
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	goToPage = type => {
		switch (type) {
			case "1":
				this.jumpPage("/bankManageList"); //去银行卡管理
				break;
			case "2":
				this.jumpPage("/myReturn"); //去小辉付账单
				break;
			case "3": //去卡卷中心
				this.props.history.push({
					pathname: "/paymentDiscount/coupon",
					query: { name: "xhqb" },
					state: {
						fromUrl: "/xhqbIndex"
					}
				});
				sessionStorage.setItem("name", "xhqb");
				break;
			case "4":
				this.handleClickPayCode(); //去付款码
				break;
			case "5": //去小辉宝
				this.props.history.push({
					pathname: "/walletHome",
					query: {
						//随便传一个参数，小辉宝主页识别query，判断是否正常返回还是关闭SDK
						from: "xhqb"
					}
				});
				break;
			case "6":
				this.props.history.push({
					pathname: "/xhdHome",
					query: {
						//随便传一个参数，小辉贷主页识别query，判断是否正常返回还是关闭SDK
						from: "xhqb"
					}
				});
				break;
			case "7":
				sessionStorage.setItem("inviteFromPage", "xhqb");
				this.props.history.push({ pathname: "/inviteHome" });
				break;
			case "8":
				this.jumpPage("/allQuestion"); //去常见问题
				break;
			case "9":
				this.jumpPage("/iframePage", {
					src: billReportUrl(),
					title: "年度账单"
				}); //年度账单
				break;
			case "10": //关注我
				modalAlert("", "关注“永辉金融”公众号，优惠早知道！", [
					{
						text: "复制公众号",
						onPress: () => {
							copy("永辉金融");
							Toast.success("复制成功，请前往微信中粘贴搜索并关注", 2);
						}
					},
					{
						text: "取消"
					}
				]);
				break;
			case "11":
				this.jumpPage("/walletBillPage"); //钱包账单
				break;
			default:
				break;
		}
	};
	//跳转小辉付账单页
	handleGoXhfBill = () => {
		const { xhfStatus } = this.state;
		if (xhfStatus === "1") {
			//已开通小辉付
			this.jumpPage("billHome");
			//设置sessionStorage(1:代表是钱包首页跳转到账单页),解决钱包点击还款,进入账单页再点击还款,再点击返回,无限在账单页和还款页返回
			sessionStorage.setItem("xhqbGoBill", 1);
		} else {
			// 未开通，去开通
			this.props.history.push({
				pathname: "/xhfHomeNoCredit",
				query: {
					//随便传一个参数，小辉付主页识别query，判断是否正常返回还是关闭SDK
					from: "xhqb"
				}
			});
		}
	};
	//baner跳转
	handleLink = value => {
		if (value.link) {
			if (value.targetArea == 0) {
				//内部
				this.props.history.push(value.link);
			} else if (value.targetArea == 1) {
				openWebView({ url: value.link });
			} else if (value.targetArea == 2) {
				this.props.history.push({
					pathname: "/iframeAgreements",
					state: {
						src: value.link,
						title: ""
					}
				});
			}
		}
	};
	//查询邀请是否可用
	queryInviteEffect(inviteActivityResp) {
		let nav = funNavs.find(item => {
			//找到导航中的推广选项
			return item.type == 7;
		});
		const { flag } = inviteActivityResp;
		if (flag) {
			nav.hidden = false;
		} else {
			nav.hidden = true;
		}
		this.setState({});
	}
	//显示金额操作
	handleShowAmt = value => {
		this.setState({
			showAmt: value
		});
	};
	//金额格式化（转化为万单位，精确到元，如12345元，显示1.2345万）
	formatAmt = amt => {
		let _amt = Number(amt);
		if (_amt >= 10000) {
			//大于等一万，精确到元，截掉“.XXX”
			let sAmt = amt.split(".")[0];
			// 截取万
			let startStr = sAmt.substring(0, sAmt.length - 4);
			//截取后四位
			let endStr = sAmt.substring(sAmt.length - 4);
			console.log(startStr, endStr, startStr + "." + endStr);
			let rAmt = startStr + "." + endStr;
			return rAmt;
		} else {
			return amt;
		}
	};
	//实名认证弹窗
	modalClick = flag => {
		this.setState({
			realVisible: flag
		});
	};
	//去实名
	goRealName = () => {
		this.props.history.push({
			pathname: "/xhqbrealnameauth"
		});
	};
	//关闭活动弹窗
	onCloseAcitve = () => {
		this.setState({
			activeVisible: false
		});
	};
	render() {
		// header配置
		const _pageParams = {
			header: {
				title: "永辉钱包",
				headerBackground:
					"linear-gradient(90deg, rgb(255, 184, 142) 0%, rgb(255, 86, 86) 100%)",
				// serviceIcon: true,
				serviceCallBack: () => {
					this.props.history.push({
						pathname: "/iframePage",
						state: {
							title: "在线客服",
							src:
								"https://jrsdk.sobot.com/chat/h5/v2/index.html?sysnum=fb2bdaba0d8c4fe2bb8ccfdf2a1f02be&channelid=3"
						}
					});
				},
				rightIcon: settingIcon,
				rightButtCallBack: () => {
					this.gotoPaymentmanagement();
				},
				goToApp: true
			},
			history: this.props.history
		};
		const {
			mobilePhone,
			selectIndex,
			totalAmount,
			totalProfit,
			titleAmt,
			titleStatus,
			xhbStatus,
			xhbAmount,
			xhbRate,
			xhfStatus,
			xhfAvailableAmount,
			xhfMaxAmount,
			xhdStatus,
			xhdAvailableAmount,
			xhdMaxAmount,
			bannerList,
			bankWelfareBanner,
			showAmt,
			realName,
			activeVisible,
			activeData,
			buttonArray,
			realExhibition
		} = this.state;
		let data = {
			xhbStatus,
			xhbAmount,
			xhbRate,
			xhfStatus,
			xhfAvailableAmount,
			xhfMaxAmount,
			xhdStatus,
			xhdAvailableAmount,
			xhdMaxAmount,
			realExhibition,
			sdkVersionCode: this.props.getAppPlatformsDatas.sdkVersionCode
		};
		return (
			<MainLayout pageParams={_pageParams}>
				<ActivityModal
					activeVisible={activeVisible}
					onCloseAcitve={this.onCloseAcitve}
					activeData={activeData}
					buttonArray={buttonArray}
					history={this.props.history}
				/>
				<div className="xhqb-index-box">
					<div className="top-info-box">
						<div className="user-info">
							<img className="info-avatar" src={xhqb_avatar} alt="" />
							<span className="info-phone">{mobilePhone}</span>
							{realName && (
								<i className="real-name" onClick={this.goRealName}>
									去实名
									<img src={real_name} />
								</i>
							)}
						</div>
						<div className="amt-info">
							<div className="amt-box">
								<span className="title">
									我的资产(元)
									{showAmt && (
										<img
											className="xianshi"
											src={ic_xianshi}
											alt=""
											onClick={() => this.handleShowAmt(false)}
										/>
									)}
									{!showAmt && (
										<img
											className="xianshi"
											src={ic_buxianshi}
											alt=""
											onClick={() => this.handleShowAmt(true)}
										/>
									)}
								</span>
								<p className="amt">
									{showAmt
										? totalAmount
											? this.formatAmt(totalAmount.replace(/[,]/g, ""))
											: "0.00"
										: "******"}
									{Number(totalAmount.replace(",", "")) >= 10000 && showAmt && (
										<span className="wan">万</span>
									)}
								</p>
								<span className="desc" onClick={() => this.goToPage("5")}>
									累计收益{" "}
									{showAmt ? (totalProfit ? totalProfit : "0.00") : "******"}
								</span>
							</div>
							<span className="shu"></span>
							<div className="amt-box" onClick={this.handleGoXhfBill}>
								<span className="title">本期账单(元)</span>
								<p className="amt">
									{showAmt ? (titleAmt ? titleAmt : "0.00") : "******"}
								</p>
								<span className="desc">{titleStatus}</span>
							</div>
						</div>
					</div>
					{/* 精选功能 */}
					<div className="jinxuan">精选功能</div>
					<div className="menu-nav">
						{funNavs.map(item => {
							return item.hidden ? (
								""
							) : (
								<div
									className="nav-item"
									onClick={() => {
										this.goToPage(item.type);
									}}
									key={item.type}
								>
									<img
										style={item.shadow ? { boxShadow: item.shadow } : {}}
										className="nav-item-img"
										src={item.icon}
										alt=""
									/>
									<span className={`nav-item-title ${item.className}`}>
										{item.name}
									</span>
								</div>
							);
						})}
					</div>
					{/* 导航tab */}
					<div className="product-box">
						<div className="title-list">
							{this.tabNavs.map((item, index) => (
								<span
									key={index}
									className={selectIndex == index ? "active" : "defult"}
									onClick={() => this.handleSelectPro(index)}
								>
									{item}
								</span>
							))}
						</div>
						<Swiper
							onRef={this.onRef}
							data={data}
							setSelect={this.handleSetSelect}
							{...this.props}
						/>
					</div>
					{/* 银行福利 */}
					<div className="jinxuan">银行福利</div>
					<div className="bank_welfare">
						<Banner
							bannerList={bankWelfareBanner}
							history={this.props.history}
						/>
					</div>
					<Banner bannerList={bannerList} history={this.props.history} />
					<div className="footer-box">
						<img className="footer" src={footer} alt="" />
					</div>
				</div>
			</MainLayout>
		);
	}
}
export default HomeIndexpage;
